package com.free.chat.filter;

import com.free.chat.common.constant.SysConstant;
import com.free.chat.entity.ApiResult;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;

import java.util.ArrayList;
import java.util.List;

/**
 * 专门验证登陆与否的过滤器
 */
// @Component
public class LoginCheckFilter implements Filter {
    // 白名单
    private static final List<String> WHITE_LIST = new ArrayList<>();

    static {
        // 登陆
        WHITE_LIST.add("/api/users/login");
        // 注册
        WHITE_LIST.add("/api/users/register");
    }

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        // 白名单
        for (String url : WHITE_LIST) {
            if (url.equals(ctx.path())) {
                chain.doFilter(ctx);
                return;
            }
        }
        Long userId = (Long) ctx.session(SysConstant.SESSION_NAME);
        if (userId == null) {
            ctx.render(ApiResult.unAuthorization());
            return;
        }
        chain.doFilter(ctx);
    }
}
